package com.cgbl.service.vm

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableField
import api.WorkServiceFactory
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.TimeUtils
import com.cgbl.service.assist.ProjectAssist
import com.cgbl.service.assist.TransferAssist
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant
import com.netease.yunxin.kit.corekit.route.XKitRouter
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.model.BaseResponse
import com.robot.base.model.MemberAdapterBean
import com.robot.base.model.PageListBean
import com.robot.base.model.ProjectBean
import com.robot.base.util.ActivityUtils
import com.robot.base.util.LiveDataEventManager
import com.robot.base.util.arouter.ARouterUtil
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent

class MyProjectDetailViewModel(application: Application) : GLBaseViewModel(application) {

    val uc = UIChangeEvent()

    var accountId = ""

    var id = ""

    var projectBean: ProjectBean? = null

    /**
     * 0 审核中 1 待启动 2已付款 3开发中 4 已完成
     */
    val type = ObservableField<Int>(1)

    val status = ObservableField<String>()

    val name = ObservableField<String>()
    val budget = ObservableField<String>()
    val time = ObservableField<String>()
    val projectType = ObservableField<String>()
    val phone = ObservableField<String>()
    val describe = ObservableField<String>()
    val service = ObservableField<String>()
    val payType = ObservableField<String>()
    val needPayPrice = ObservableField<String>()
    val paidPrice = ObservableField<String>()
    val startDate = ObservableField<String>()
    val endDate = ObservableField<String>()
    val lastEndDate = ObservableField<String>()
    val orderNo = ObservableField<String>()


    val accountList = arrayListOf<MemberAdapterBean>()

    /**
     * 已关闭原因
     */
    val remake = ObservableField<String>()

    val remakeTime = ObservableField<String>()

    val kfName = ObservableField<String>()

    /**
     * 预付款
     */
    val price = ObservableField<String>()

    val clickUpdateCommand = BindingCommand<Any>(BindingAction {

    })

    //再次发布
    val clickCloseCommand = BindingCommand<Any>(BindingAction {
        uc.showCloseDialog.call()
    })

    val clickEndProjectCommand = BindingCommand<Any>(BindingAction {
        uc.showEndProjectEvent.call()
    })

    val clickMemberFrameCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Project.A_MEMBER_FRAME)
    })

    /**
     * 群聊沟通
     */
    val toChatCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Project.A_SELECT_TEAM)
    })
    val toBalanceCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Project.A_BALANCE_PROJECT)
    })

    /**
     * 沟通
     */
    val toPersonalChatCommand = BindingCommand<Any>(BindingAction {
        sendMessage()
    })

    /**
     * 支付尾款
     */
    val toSubmitCommand = BindingCommand<Any>(BindingAction {
        submitProject()
    })

    class UIChangeEvent {

        val showCloseDialog = SingleLiveEvent<Void>()

        val showEndProjectEvent = SingleLiveEvent<Void>()

    }


    fun fetchProjectProfile(id: String) {
        this.id = id
        ProjectAssist.initCurrentProject(id)
        WorkServiceFactory.get(id)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<ProjectBean>>(this) {
                override fun onNext(t: BaseResponse<ProjectBean>) {
                    projectBean = t.data
                    accountId = t.data.accountId ?: ""
                    ProjectAssist.initCurrentProjectMembers(projectBean?.accountDOS ?: listOf())
                    type.set(t.data.status?.toIntOrNull())
                    status.set(TransferAssist.transferStatusText(t.data.status ?: ""))
                    name.set(t.data.itemName)
                    budget.set("¥${t.data.itemBudget}")
                    time.set(t.data.itemCycle)
                    projectType.set(t.data.labelName)
                    phone.set(t.data.itemPhone)
                    describe.set(t.data.itemInfo)
                    service.set(t.data.customerId)
                    accountList.clear()
                    accountList.addAll(t.data.accountDOS ?: listOf())
                    payType.set(if (t.data.payType == "0") "全款" else "预付款+尾款")
                    needPayPrice.set("¥${t.data.duesPrice}")
                    paidPrice.set("¥${t.data.paidPrice}")
                    startDate.set(
                        TimeUtils.millis2String(
                            t.data.startTime?.toLong() ?: 0, "yyyy-MM-dd"
                        )
                    )
                    endDate.set(
                        TimeUtils.millis2String(
                            t.data.endTime?.toLong() ?: 0, "yyyy-MM-dd"
                        )
                    )
                    lastEndDate.set(
                        TimeUtils.millis2String(
                            t.data.lastEndTime?.toLong() ?: 0, "yyyy-MM-dd"
                        )
                    )
                    orderNo.set(t.data.id)
                }
            })
    }

    /**
     * "itemName": "测试全流程", //项目名称
    "itemBudget": 19000, //项目预算
    "itemCycle": "12月", //交付周期
    "itemInfo": "测试项目", //项目内容
    "itemFile": "http://ssss", //项目文件
    "itemPhone": "15200000000", //联系电话
    "accountId": "24", //用户编码
    "duesPrice": 19000, //应付金额
    "paidPrice": 2000, //已付金额
    "startTime": 1684671160000, //开始时间
    "endTime": 1684671160000, //结束时间
    "lastEndTime": null, //最晚结束时间
    "customerId": "1660233953093890049", //所属客服
    "itemTypeId": "12", //项目类型
    "customerAccountId": "24", //所属客服基础用户编码
    "id": "1660577486241853441", //项目编码
    "createTime": 1684776299000,
    "appItemInfoAccountCreateReqVOS": [
    {
    "career": "0", //职业
    "accountId": 0,
    "career": "",
    "itemAccountId": 0,
    职称，根据字典获取
    "itemAccountId": 1647632285206704000, //开发者用户ID
    "wages": 4000 //薪资
    }
    ]
     */
    fun updateProject() {
        if (projectBean == null) return
        WorkServiceFactory.updateItemInfo(projectBean)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
                override fun onNext(t: BaseResponse<String>) {

                }
            })
    }

    private fun submitProject() {
        val params = mapOf("id" to id)
        WorkServiceFactory.updateStatus(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
                override fun onNext(t: BaseResponse<String>) {
                    LiveDataEventManager.postRefreshProjectListEvent()
                    finish()
                }
            })
    }

    fun sendMessage() {
        if (TextUtils.isEmpty(accountId)) return
        XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE)
            .withParam(RouterConstant.CHAT_ID_KRY, accountId)
            .withContext(ActivityUtils.getTopActivity()).navigate()
    }
}